/* api */
import { getStateColorMap } from '@src/api/SettingApi.ts'
import { getTaskAllotDispatchTeamUserList } from '@src/api/TaskApi.ts'
import { getCustomerExeinsyn } from '@src/api/CustomerApi'
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
/* component */
import ContactUserItem from '@src/component/common/BaseContact/ContactUserItem.vue'
/* model */
import Page from '@model/Page'
import { isOpenData } from '@src/util/platform'

const TaskAllowSelect = {
  name: 'task-allot-select',
  props: {
    taskConfig: {
      type: Object,
      default: () => ({})
    },
    /** 可以选择的派单类型 */
    typeOptions: {
      type: Array,
      default: () => ['pool', 'normal', 'auto', 'allot']
    }
  },
  data() {
    return {
      isOpenData,
      allotType: 'normal',
      allotTypeMap: {
        pool: {
          text: '派单到工单池',
          value: 'pool'
        },
        normal: {
          text: '派单到工单负责人',
          value: 'normal'
        },
        auto: {
          text: '自动分配',
          value: 'auto'
        },
        allot: {
          text: '保存至待分配列表',
          value: 'waitDistribution'
        }
      },
      value: {
        executors: [],
        synergies: []
      },
      selectTeams: [],
      stateColorMap: {},
      teamUserPage: new Page()
    }
  },
  components: {
    [ContactUserItem.name]: ContactUserItem
  },
  computed: {
    /* 自动派单 */
    autoDispatch() {
      return this.taskConfig?.autoDispatch === true;
    },
    /* 是否按团队派单 */
    isAllotByTag() {
      return this.taskConfig?.allotByTag === true;
    },
    /* 是否显示选择负责人 */
    isShowSelectExecutor() {
      return this.allotType === this.allotTypeMap.normal.value;
    },
    /* 是否开启工单池 */
    taskPoolOn() {
      return this.taskConfig.taskPoolOn === true && this.typeOptions.includes('pool');
    }
  },
  watch: {
    'allotType'(newValue) {
      this.$emit('update:type', newValue);
    },
    typeOptions(newVal) {
      // 只有一项选项，赋值allotType
      if(Array.isArray(newVal)) {
        if(newVal.length === 1) {
          this.allotType = newVal[0];
        }
      }
    }
  },
  mounted() {
    this.fetchStateColor()
  },
  methods: {
    changeAllotData(data = {}) {
      const { allotType, synergies, executors } = data;
      
      if (allotType) this.allotType = allotType;
      if (synergies && Array.isArray(synergies)) this.value.synergies = synergies.filter(synergie => !!synergie.userId);
      if (executors && Array.isArray(executors)) this.value.executors = executors.filter(executor => !!executor.userId);
      
    },
    clearExecutors() {
      this.value.executors = [];
    },
    deleteSynergie(index) {
      this.value.synergies.splice(index, 1);
    },
    emitUpdateExecutor() {
      this.$emit('update:executors', this.value.executors)
    },
    /** 根据客户id获取客户信息和客户负责人信息和开关 */
    fetchExeinsynWithCustomerManager(customerId = '') {
      if(!customerId) return console.warn('fetchExeinsynWithCustomerManager paramer not have customerId')
      
      getCustomerExeinsyn({ id: customerId}).then(result => {
        let exeInSynOfTaskOrEvent = result?.data?.exeInSynOfTaskOrEvent;
        // 允许自动将客户负责人带入工单或事件协同人
        if(exeInSynOfTaskOrEvent) {
          let synergies = this.value.synergies.slice();
          let isHaveSynergies = synergies.some(synergies => synergies.userId === result?.data?.userId)
          !isHaveSynergies && result.data.userId && this.value.synergies.push(result.data)
        }
      })
      
    },
    /** 
     * @description 获取团队人员列表
    */
    fetchTeamUsers(selectParams) {
      
      this.teamUserPage = new Page()
      
      let params = {
        keyword: selectParams.keyword,
        pageNum: selectParams.pageNum,
        tagId: this.selectTeams ? this.selectTeams.map(team => team.id).join(',') : ''
      }
      
      return (
        getTaskAllotDispatchTeamUserList(params)
          .then((result = {}) => {
            this.teamUserPage.merge(result)
            
            result.list = result.list.map(user =>
              Object.freeze({
                label: user?.displayName || '',
                value: user?.userId || '',
                ...user
              }))
            
            return result
            
          })
          .catch(error => {
            console.error(error)
          })
      )
    },
    /** 初始化工作状态的颜色 */
    fetchStateColor() {
      return (
        getStateColorMap()
          .then((res) => {
            this.stateColorMap = res || {}
          })
          .catch(err => console.error(err))
      )
    },
    /**
     * @description 选择团队变化事件
    */
    handlerTeamChange(value) {
      this.selectTeams = value
    },
    /**
     * @description 选择团队成员变化事件
    */
    handlerTeamUsersChange(users) {
      // 设置负责人信息
      this.value.executors = users || []
      this.emitUpdateExecutor()
    },
    /** 选择协同人人员  */
    selectSynergiesUser() {
      let choose = 'dept';
      let options = {
        title: '请选择工单协同人',
        max: 100,
        selected: this.value.synergies,
        mode: BaseSelectUserModeEnum.Filter
      };
    
      this.$fast.select.multi.user(options)
        .then(res => {
          if(res.status != 0) return
          this.value.synergies = res?.data?.users || [];
          this.$emit('update:synergies', this.value.synergies);
        })
        .catch(err => {
          console.warn(err)
        })
    },
    /** 选择负责人人员  */
    selectExecutorUser() {
      let choose = this.isAllotByTag ? 'team' : 'dept';
      let options = {
        title: '请选择工单负责人',
        max: 1,
        selectedUsers: (
          this.isAllotByTag 
            ? { users: this.value.executors } 
            : this.value.executors
        ),
        mode: BaseSelectUserModeEnum.Filter
      };
      
      this.$fast.select.single.user(choose, options)
        .then(res => {
          if(res.status != 0) return
          this.value.executors = res?.data?.users || [];
          this.emitUpdateExecutor()
        })
        .catch(err => {
          console.warn(err)
        })
    }
  }
}

export default TaskAllowSelect